<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <strong style="font-size: 20px;">
          考勤记录
        </strong>
      </el-col>
      <el-col :span="20" align="right">
        <span style="margin-right: .5em">
          <el-date-picker
            v-model="search.date"
            type="date"
            placeholder="日期"
            style="width: 200px;"
            size="medium"
            :editable="false"
            :clearable="false"
            value-format="yyyy/MM/dd"
            @change="filterGenerate();dataProcessor()"
          />
        </span>
        <span style="margin-right: .5em">
          <el-button :loading="syncLoading" size="medium" type="success" @click="sync()">同步数据</el-button>
        </span>
        <!-- <span style="margin-right: .5em">
          <el-button :loading="processLoading" size="medium" type="primary" @click="process()">计算处理</el-button>
        </span> -->
        <!-- <span style="margin-right: .5em">
          <el-button :loading="settleLoading" size="medium" type="success" plain @click="settle()">确认</el-button>
        </span> -->
      </el-col>
    </el-row>

    <el-row>
      <el-table
        v-loading="loading"
        :data="list"
        element-loading-text="加载中..."
        fit
        lazy
        stripe
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column fixed prop="id" label="id" />
        <el-table-column fixed label="班次">
          <template slot-scope="scope">
            <span>{{ scope.row.type.__toString }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed label="员工">
          <template slot-scope="scope">
            <span>{{ scope.row.staff.__toString }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed label="是否确认">
          <template slot-scope="scope">
            <div slot="reference">
              <el-tag v-if="scope.row.settled" type="success">是</el-tag>
              <el-tag v-else type="danger">否</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="penaltyOnMinutes" label="迟到(分钟)" width="90" />
        <el-table-column prop="penaltyOnAmount" label="迟到扣罚" />
        <el-table-column label="迟到免罚">
          <template slot-scope="scope">
            <div v-if="scope.row.penaltyOnAmount > 0" slot="reference">
              <el-switch v-model="scope.row.penaltyOnFree" :disabled="scope.row.settled" size="medium" @change="changeOnOffAmount(scope.row.id,0,$event)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="penaltyOffMinutes" label="早退(分钟)" width="90" />
        <el-table-column prop="penaltyOffAmount" label="早退扣罚" />
        <el-table-column label="早退免罚">
          <template slot-scope="scope">
            <div v-if="scope.row.penaltyOffAmount > 0" slot="reference">
              <el-switch v-model="scope.row.penaltyOffFree" :disabled="scope.row.settled" size="medium" @change="changeOnOffAmount(scope.row.id,1,$event)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="penaltyAmount" label="总扣罚" />
        <el-table-column prop="originSalary" label="底薪" />
        <el-table-column prop="salary" label="发放金额" />
        <el-table-column label="结算至队长">
          <template slot-scope="scope">
            <span>{{ scope.row.staff.__metadata.divideToLeader }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结算至经纪人">
          <template slot-scope="scope">
            <span>{{ scope.row.staff.__metadata.divideToBroker }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" width="170">
          <template slot-scope="scope">
            <span v-if="scope.row.startTime">{{ new Date(scope.row.startTime ) | dateFormat('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="170">
          <template slot-scope="scope">
            <span v-if="scope.row.endTime">{{ new Date(scope.row.endTime ) | dateFormat('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template scope="scope">
            <el-button v-if="!scope.row.settled && (!scope.row.startTime || !scope.row.endTime)" size="small" plain @click="replacement(scope.row.id)">补打卡</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      syncLoading: false,
      processLoading: false,
      settleLoading: false,

      list: [],
      search: {
        date: null
      }
    }
  },
  created() {
    const today = new Date()
    const yesterday = new Date(today.getTime() - 86400000)
    this.search.date = `${yesterday.getFullYear()}/${yesterday.getMonth() + 1}/${yesterday.getDate()}`
    this.filterGenerate()
    this.dataProcessor()
  },
  methods: {
    replacement(id) {
      this.axios.post(`/officer/attendance-records/${id}/replacement`)
        .then(res => {
          this.$message.success('修改成功!')
        })
        .finally(() => { this.dataProcessor() })
    },
    changeOnOffAmount(id, type, event) {
      const data = {}
      if (type > 0) {
        data.penaltyOffFree = event
      } else {
        data.penaltyOnFree = event
      }
      this.axios.put(`/officer/attendance-records/${id}`, data)
        .then(res => {
          this.$message.success('修改成功!')
          this.$forceUpdate()
        })
        .finally(() => { this.dataProcessor() })
    },
    sync() {
      this.syncLoading = true
      this.axios.post(`/officer/attendance-logs/sync`, null, { params: {
        '@filter': `entity.getDate() >= datetime.get('${this.search.date} 00:00:00') && entity.getDate() <= datetime.get('${this.search.date} 23:59:59')`
      }})
        .then((res) => {
          this.axios.post(`/officer/attendance-records/process`, null, { params: {
            '@filter': `entity.getDate() >= datetime.get('${this.search.date} 00:00:00') 
                     && entity.getDate() <= datetime.get('${this.search.date} 23:59:59')`
          }})
            .then((process) => {
              this.$message.success('同步成功!')
              this.dataProcessor()
            })
            .catch((err) => {
              console.error(err)
            })
            .finally(() => { this.syncLoading = false })
        })
        .catch(() => {
          this.syncLoading = false
        })
    },
    process() {
      this.processLoading = true
      this.axios.post(`/officer/attendance-records/process`, null, { params: {
        '@filter': `entity.getDate() >= datetime.get('${this.search.date} 00:00:00') && entity.getDate() <= datetime.get('${this.search.date} 23:59:59')`
      }})
        .then((res) => {
          this.$message.success('计算完毕!')
          this.dataProcessor()
        })
        .catch((err) => {
          console.error(err)
        })
        .finally(() => { this.processLoading = false })
    },
    settle() {
      this.settleLoading = true
      this.axios.post(`/officer/attendance-records/settle`, null, { params: {
        '@filter': `entity.getDate() >= datetime.get('${this.search.date} 00:00:00') 
                 && entity.getDate() <= datetime.get('${this.search.date} 23:59:59') 
                 && entity.getSettled() == false`
      }})
        .then((res) => {
          this.$message.success('确认完毕!')
          this.dataProcessor()
        })
        .catch((err) => {
          console.error(err)
        })
        .finally(() => { this.settleLoading = false })
    },
    handleDelete(row) {
      console.log(row)
    },
    filterGenerate() {
      this.filter = {
        '@filter': `entity.getDate() >= datetime.get('${this.search.date} 00:00:00') && entity.getDate() <= datetime.get('${this.search.date} 23:59:59')`,
        '@order': 'entity.staff.squad|ASC,entity.staff.id|ASC',
        '@expands': "['entity.staff']",
        limit: 10000000
      }
    },
    dataProcessor() {
      this.loading = true
      // table数据
      this.axios.get(`/officer/attendance-records`, {
        params: Object.assign(
          {},
          this.filter
        )
      }).then(res => {
        this.list = res.data
        this.loading = false
      })
    }
  }
}
</script>
